package world.liquor.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import world.liquor.domain.BeerAssessment;
import world.liquor.domain.BeerInfo;
import world.liquor.service.BeerAssessmentService;
import world.liquor.service.RecommendService;
import world.member.domain.Member;


@Controller
public class RecommendController {
	
	private RecommendService recommendService;	
	private BeerAssessmentService service2;
	
	public RecommendController() {
	}
	@Autowired
	public RecommendController(RecommendService recommendService, BeerAssessmentService service2) {
		this.recommendService = recommendService;
		this.service2=service2;
	}

   // 맥주 추천
	@RequestMapping("/liquor/beerRecommend.do")
	public String beerRecommend(ModelMap map, HttpSession session) throws Exception{
		HashMap<String, BeerInfo> beerRecommendList=new HashMap<String, BeerInfo>();
		Member member=(Member)session.getAttribute("login_member");
		if(member==null){
			map.addAttribute("result", beerRecommendList);		
			map.addAttribute("message", "로그인을 먼저 해주세요");
			return "/recommend/recommend.jsp";
		}
		String memberId=member.getMemberId();
		try{
			// 추천 맥주 리스트
			beerRecommendList=recommendService.beerRecommend(memberId);
			if(beerRecommendList.size()==0){
				map.addAttribute("result", beerRecommendList);		
				map.addAttribute("message", "추천할 맥주가 없습니다.");
				return "/recommend/recommend.jsp";
			}
		}catch(Exception e){
			map.addAttribute("message", e.getMessage());
			return "/recommend/recommend.jsp";
		}
		ArrayList<BeerAssessment> list_as = common(session);
		map.addAttribute("result", beerRecommendList);
		map.addAttribute("result2", list_as);
		map.addAttribute("message", "추천 맥주");
		return "/recommend/recommend.jsp";
	}
	
	// 메인 페이지에 정보 제공 (평점이 가장 높은 맥주)
	@RequestMapping("/liquor/index.do")
	public String index(ModelMap map) throws Exception{
		HashMap result=recommendService.beerBest();
		map.addAllAttributes(result);
		return "/index.jsp";
	}
	
	
	//공통 메서드 - 회원별로 평가한 assessment 점수목록 list_as를 보내주기 위한 메서드
		public ArrayList<BeerAssessment> common(HttpSession session) throws SQLException{
			Member m = (Member)session.getAttribute("login_member");
			if(m!=null){ //session값이 있을 경우에만 list_as 리턴
				String memberId = m.getMemberId();
				ArrayList<BeerAssessment> list_as = service2.selectAssessmentByMemberId(memberId);
				return list_as;			
			}
			return null;
		}

}
